package com.ygxsk.carhome.ui.order;

import android.os.Bundle;
import android.view.View;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.ygxsk.carhome.R;
import com.ygxsk.carhome.constant.ExtraKey;
import com.ygxsk.carhome.listener.ClickJumpToOrderDetailListener;
import com.ygxsk.carhome.response.MyOrderBean;
import com.ygxsk.carhome.sys.Session;
import com.ygxsk.carhome.ui.BaseImmersionFragment;
import com.ygxsk.carhome.ui.adapter.OrderTransAdapter;
import com.ygxsk.integrated.retrofit.Parameterkey;

import java.util.ArrayList;

import butterknife.BindView;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link OrderListFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class OrderListFragment extends BaseImmersionFragment {

    private String messageNull = "暂无订单，快去下单吧~";


    @BindView(R.id.refreshlayoutinleadsfragment)
    SmartRefreshLayout refreshLayoutInLeadsFragment;

    @BindView(R.id.recyclerviewinleadlistfragment)
    RecyclerView recyclerViewInLeadListFragment;


    //最后一条上传的id的信息内容
    private int pagination_upLoad = Parameterkey.pageNum_default_first;


    private View view_orderfragment;

    /**
     * 上传订单最后一条id
     */
    private String orderIdPass;

    /**
     * 上传订单状态,默认是全部订单内容
     */
    private String orderStatePass = "";

    /**
     * 订单列表的实体信息内容
     */
    private ArrayList<MyOrderBean> mDataResources = new ArrayList<MyOrderBean>();

    //关于当Fragment可见的时候开始加载数据
    protected boolean isVisible;

    private boolean isViewPrepared;

    /**
     * 下拉刷新布局内容
     */
    private SmartRefreshLayout refreshLayoutInFragment;

    /**
     * 装载数据的适配器内容
     */
    private OrderTransAdapter orderTransAdapter;


    public OrderListFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment LeadListFragment.
     */
//    public static LeadListFragment newInstance(String param1, String param2) {
    public static OrderListFragment newInstance() {

        OrderListFragment fragment = new OrderListFragment();
        Bundle args = new Bundle();
//        args.putString(ARG_PARAM1, param1);
//        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);

        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

//        if (getArguments() != null) {
//            mParam1 = getArguments().getString(ARG_PARAM1);
//            mParam2 = getArguments().getString(ARG_PARAM2);
//        }

        mFragmentInstance = this;
        mActivityInstance = this.getActivity();

        mSession = Session.get(this.getActivity());

        if (getArguments() != null) {
//            //2020 这个值 是从上个界面写死的，也是传递过来的值内容
//            arg_status = getArguments().getInt(ARG_STATUS);
//            //mParam2 = getArguments().getString(ARG_PARAM2);
//
//            flag_jumpfrom_where = getArguments().getInt(ARG_JUMPFROM);
//
//            if (arg_status == 0) {
//                consumeStatus_Pass = "3";//【已接单】的未处理的单子 传递3
//            } else if (arg_status == 1) {
//                consumeStatus_Pass = "4";//【已完成】的服务单 ，已提交核销码，已核销传递6
//            }
        }

        //列表之内需要向外部广播数据
//        if (!EventBus.getDefault().isRegistered(this)) {
//            EventBus.getDefault().register(this);
//        }


    }

    @Override
    protected void gainDatas() {

        //2018/12/11 界面未完成又不是可见的那么直接返回
        if (!isViewPrepared || !isVisible) {
            //LogUtils.d("itchen----->走到了不能展示逻辑");
            return;
        }

        //这个接口内就是刷新全部内容
        pagination_upLoad = 1;//重置

        if (mDataResources != null && !mDataResources.isEmpty()) {
            mDataResources.clear();
        }

//        if (leadListItemAdapter != null) {
//            leadListItemAdapter.notifyDataSetChanged();
//        }

        if (NetworkUtils.isConnected()) {

            //真实调试放开
//            getServerDatas(consumeStatus_upLoad, pagination_upLoad);

        } else {
            //是否有其他的执行逻辑？
            netWorkError();
            setEnableLoadmore(refreshLayoutInLeadsFragment, false);
        }

    }

    private void getServerDatas(String consumeStatus_upLoad, int pagination_upLoad) {

//        HashMap<String, Object> map = new HashMap<>();
//        map.put(Parameterkey.pageNum, pageNum_upLoad);//,
//        map.put(Parameterkey.pageSize, pageSize_upLoad);//,
//        map.put(Parameterkey.keyWord, keyWord_upLoad);//,
//
//        AddLogUpLoadInfo addLogUpLoadInfo = new AddLogUpLoadInfo();
//        addLogUpLoadInfo.setActivity(mActivityInstance);
//        addLogUpLoadInfo.setWhat(ConstantApi.WHAT_BUSINESSLEDGERLIST);//请求数字标识
//        addLogUpLoadInfo.setUrlPath(ApiService.businessLedgerListUrl);//url地址
//        addLogUpLoadInfo.setRequestMethod(ConstantSign.REQUEST_METHOD_GET);//POST 或者 GET
//        addLogUpLoadInfo.setToastToUser(true);//展示给用户的标志
//        addLogUpLoadInfo.setHashMapParameter(map);
//
//        NetworkManager.getInstance().initRetrofitRxJava()
//                .create(ApiService.class)
//                // .businessLedgerList()
//                .businessLedgerList(NetworkManager.getInstance().getBeforeSwitchUrl(), RequestBody.create(JSON.toJSONString(map, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue), MediaType.parse(ApiService.HEADER_JSON)))
//                .compose(WorkBookHistoryActivity.this.bindUntilEvent(ActivityEvent.DESTROY))//
//                .compose(new ResponseTransformer<>(addLogUpLoadInfo, new ApiRequestSubListener<WorkBookFirstNodeOutSideBean>() {
//                    @Override
//                    public void handlerSomeThingNotSuccessDataForItSelf(int what_method, String serverCode, String serverMessage) {
//                        super.handlerSomeThingNotSuccessDataForItSelf(what_method, serverCode, serverMessage);
//                        methodNotSuccessData(what_method, serverCode, serverMessage);
//                    }
//                })).doOnSubscribe(new Consumer<Disposable>() {
//                    @Override
//                    public void accept(Disposable disposable) throws Throwable {
//
//                        loadingGone();
//
//                        if (refreshLayoutInWorkHistory != null) {
//                            refreshLayoutInWorkHistory.setEnableLoadMore(true);
//                        }
//
//                    }
//                }).subscribe(new Consumer<WorkBookFirstNodeOutSideBean>() {
//                    @Override
//                    public void accept(WorkBookFirstNodeOutSideBean workBookFirstNodeOutSideBean) throws Throwable {
//
//                        if (workBookFirstNodeOutSideBean != null) {
//
//                            if (workBookFirstNodeOutSideBean.getRows() != null && !workBookFirstNodeOutSideBean.getRows().isEmpty()) {
//
//                                if (mDataResource != null) {
//                                    mDataResource.addAll(workBookFirstNodeOutSideBean.getRows());
//                                }
//
//                            }
//
//                            //列表接口需增加分页参数：pageNum:页码(首次默认传1)，pageSize:每页记录条数
//                            //总的数据列表总数值
//                            //int totalCounts = messageBean.getTotal();
//                            totalPageNumberCount = setSmartPaging(workBookFirstNodeOutSideBean.getTotal(), refreshLayoutInWorkHistory);
//
//                        }
//
//                        //这里也不用管是下拉刷新或者上拉加载更多，直接判断是否为空，
//                        if (mDataResource != null && mDataResource.isEmpty()) {
//
//                            //同时禁用加载更多；
//                            if (refreshLayoutInWorkHistory != null) {
//                                refreshLayoutInWorkHistory.setEnableLoadMore(false);
//                            }
//
//                            fillNullDataView(StringUtils.getString(R.string.nulldatanow), R.drawable.errorsear);
//                        }
//
//                        if (workBookFirstNodeProvider != null) {
//                            workBookFirstNodeProvider.notifyDataSetChanged();
//                        }
//
//                    }
//                }, new ErrorConsumer() {
//
//                    @Override
//                    protected void error(ApiException apiException) {
//
//                        //页面报错；
//
//                    }
//                });

    }

    /**
     * 订单详情的列表顶部订单编号和内侧的小适配器点击均进入详情
     */
    private class ClickJumpToOrderDetailListenerSub implements ClickJumpToOrderDetailListener {

        @Override
        public void clickJumpToOrderDetail(MyOrderBean myOrderBeanItem) {

            if (myOrderBeanItem != null) {
                Bundle bundle = new Bundle();
                bundle.putString(ExtraKey.EXTRA_ORDER_NUMBER, myOrderBeanItem.getOrderNo());
                ActivityUtils.startActivity(bundle, OrderDetailActivity.class);
            }

        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_lead_list;
    }


    @Override
    public void onClickNodata(View view) {
        gainDatas();
    }
}